package com.dimao.certificate_build_service.http.kotiln

import com.dimao.certificate_build_service.Util.StrUtil
import com.dimao.certificate_build_service.Util.TimeUtil
import com.dimao.certificate_build_service.http.Api
import com.dimao.certificate_build_service.http.FailedReply
import com.dimao.certificate_build_service.http.SucceededReply
import com.dimao.certificate_build_service.pdf.kotiln.PDFBuilder
import com.dimao.certificate_build_service.pdf.kotiln.PDFMerge
import io.vertx.core.json.JsonArray
import io.vertx.ext.web.RoutingContext
import io.vertx.kotlin.coroutines.awaitResult
import io.vertx.kotlin.coroutines.dispatcher
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlin.collections.ArrayList

class GetMultipleTemporaryPDFApi : Api, AsyncApi<String> {
    @ExperimentalCoroutinesApi
    override fun run(context: RoutingContext?) {
        val future = GlobalScope.async(context!!.vertx().dispatcher()) { asyncRun(context) }
        future.invokeOnCompletion {
            context.response().putHeader("Content-Type", "application/json; charset=UTF-8")
            val error = future.getCompletionExceptionOrNull()
            if(error != null)
                context.response().end(
                        FailedReply(error)
                                .toJson()
                                .toBuffer()
                )
            else context.response().end(
                    SucceededReply(future.getCompleted())
                            .toJson()
                            .toBuffer()
            )
        }
    }

    override suspend fun asyncRun(context: RoutingContext): String {
        val jsonArray = JsonArray(context.bodyAsString)
        val vertx = context.vertx()
        val pdfFileNames = ArrayList<String>(jsonArray.size())

        for(i in jsonArray.list.indices){
            val taskID = jsonArray.getJsonObject(i)
                    .getString("task_id")
            val certificateID = jsonArray.getJsonObject(i)
                    .getString("certificate_id")

            pdfFileNames.add("${PDFBuilder.config.saveTemporaryPDFPath}/$taskID/$certificateID.pdf")
        }

        val fileName = "${PDFBuilder.config.saveTemporaryPDFPath}/${TimeUtil.getCurrentDate(true)}_${StrUtil.generateShortUuid()}.pdf"

        val buffer = PDFMerge.merge(vertx, pdfFileNames)
        awaitResult<Void> { h -> vertx.fileSystem().writeFile(fileName, buffer, h) }

        return fileName
    }
}